<?php
namespace CouchPHP;

/**
 * Response class
 * @package CouchPHP
 * @author Jakub `Kofel` Kaflik
 */
class Response
{
    /**
     * Response headers (key=>value)
     * @var array
     */
    public $headers = array();
    
    /**
     * Response content
     * @var string
     */
    public $content;
    
    /**
     * Raw response
     * @var string
     */
    public $raw;
    
    /**
     * Response status code
     * @var int
     */
    public $status;
    
    /**
     * Parse raw content to content and key=>value headers array
     * @param string $raw 
     */
    public function __construct( $raw )
    {
        $this->raw = $raw;
        
        list( $temp, $this->content ) = explode( "\r\n\r\n", $raw );
        
        $temp = explode( "\n", $temp );
        
        foreach( $temp as $lol )
        {
            if( strpos($lol, ": ") === false )
            {
                $match = array();
                if( preg_match( "#HTTP/1.0 (.*?) #si", $lol, $match ) )
                        $this->status = (int) $match[1];
                            
                continue;                
            }

            list( $key, $value ) = explode( ": ", $lol );
            $this->headers[ $key ] = trim($value);
        }
    }
    
    /**
     * Returns JSON of response
     * @var mixed
     */
    public function json()
    {
       return json_decode( $this->content ); 
    }
    
    /**
     * Returns content
     * @return string
     */
    public function __toString()
    {
        return $this->content;
    }
}
